package com.openxt.nbzj.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.openxt.nbzj.R;
import com.openxt.nbzj.activity.WebViewActivity;
import com.openxt.nbzj.adapter.SpecialListAdapter;
import com.openxt.nbzj.call.AccessStatisticsManager;
import com.openxt.nbzj.model.ConfigModel;
import com.openxt.nbzj.model.RemotingModel;
import com.openxt.nbzj.remoting.RemotingEx;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.BindView;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;

/**
 * Created by 颖杰_2 on 2016/7/10.
 */
public class SpecialFragment extends OpenxtFragment implements AdapterView.OnItemClickListener, RemotingEx.OnActionListener {
    @BindView(R.id.ptrClassicFrameLayout)
    PtrClassicFrameLayout ptrClassicFrameLayout;
    @BindView(R.id.listView)
    ListView listView;

    boolean isLoading = false;
    Handler mHandler = new Handler();

    List<JSONObject> mList = new ArrayList<>();
    SpecialListAdapter specialListAdapter = null;
    Context mContext = null;
    RemotingModel remotingModel = null;

    private int pageIndex = 1;
    private int pageSize = 10;
    private Long timeStamp = null;
    private int total = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.special_fragment, container, false);
        ButterKnife.bind(this, view);

        TextView tv = (TextView) view.findViewById(R.id.openxt_title);
        tv.setText("专题");

        LinearLayout btn = (LinearLayout) view.findViewById(R.id.openxt_title_left);
        btn.setVisibility(View.GONE);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();

        remotingModel = new RemotingModel(mContext);
        specialListAdapter = new SpecialListAdapter(mContext, mList);
        listView.setAdapter(specialListAdapter);
        listView.setOnItemClickListener(this);

        ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            pageIndex = 1;
                            timeStamp = null;
                            ptrClassicFrameLayout.setLoadMoreEnable(false);
                            doLoad();
                        } catch (Exception e) {
                        }
                    }
                }, 10);
            }
        });

        ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            pageIndex++;
                            doLoadMore();
                        } catch (Exception e) {
                        }
                    }
                }, 10);
            }
        });
    }

    private void doLoad(){
        remotingModel.getSpecialGetNative(this, false, pageIndex, pageSize, null, timeStamp);
    }

    private void doLoadMore(){
        remotingModel.getSpecialGetNative(this, false, pageIndex, pageSize, "$more", timeStamp);
    }

    @Override
    public void refresh() {
        AccessStatisticsManager.instance().start(mContext, "#/special", true);

        if(isLoading)
            return;

        //获取缓存
        final String val = Utils.getLocalStorage(mContext, ConfigModel.SPECIAL_GET_NATIVE);
        if(!StringUtil.isNull(val)){
            isLoading = true;
            mList.clear();
            specialListAdapter.notifyDataSetChanged();
            try{
                JSONArray array = JSON.parseArray(val);
                for(int i = 0, j = array.size(); i < j; i++){
                    pageIndex = i + 1;
                    JSONObject item = array.getJSONObject(i);
                    JSONArray rows = item.getJSONArray("rows");
                    if(rows == null)
                        continue;
                    for(int m = 0, n = rows.size(); m < n; m++){
                        mList.add(rows.getJSONObject(m));
                    }

                    timeStamp = item.getLong("timeStamp");
                    total = item.getInteger("total");
                }
                specialListAdapter.notifyDataSetChanged();

                if(total > (pageIndex * pageSize))
                    ptrClassicFrameLayout.setLoadMoreEnable(true);
                else
                    ptrClassicFrameLayout.setLoadMoreEnable(false);

                listView.setAdapter(specialListAdapter);
            }catch (Exception e){
            }
        }else if (ActivityUtil.isNetworkAvailable(mContext)) {
            ptrClassicFrameLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ptrClassicFrameLayout.autoRefresh(true);
                }
            }, 0);
        }
        isLoading = true;
    }

    @Override
    public void willBeDisplayed() {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(!ActivityUtil.isNetworkAvailable(mContext)){
            showMsg("无网络，请先查看网络是否正常打开");
            return;
        }
        Utils.setLocalStorage(mContext, ConfigModel.NATIVE_PAGENAME, getActionUrl());
        Bundle bundle = new Bundle();
        JSONObject item = mList.get(position);
        String RedirectURL = item.getString("RedirectURL");
        bundle.putString("url", ConfigModel.ROOTPATH + RedirectURL);
        toActivity(WebViewActivity.class, bundle, false);
    }

    @Override
    public void onActionCompleted(String reVal, String actionName) {
        try {
            if(pageIndex == 1)
                Utils.removeLocalStorage(mContext, ConfigModel.SPECIAL_GET_NATIVE);

            JSONObject data = JSON.parseObject(reVal);
            final String val = Utils.getLocalStorage(mContext, ConfigModel.SPECIAL_GET_NATIVE);
            JSONArray cacheArray = null;
            if(StringUtil.isNull(val)){
                cacheArray = new JSONArray();
                cacheArray.add(data);
                Utils.setLocalStorage(mContext, ConfigModel.SPECIAL_GET_NATIVE, cacheArray.toString());
            }else{
                cacheArray = JSON.parseArray(val);
                if(cacheArray.size() < 5) {
                    cacheArray.add(data);
                    Utils.setLocalStorage(mContext, ConfigModel.SPECIAL_GET_NATIVE, cacheArray.toString());
                }
            }
            total = data.getInteger("total");
            timeStamp = data.getLong("timeStamp");
            JSONArray rows = data.getJSONArray("rows");
            if (ConfigModel.SPECIAL_GET_NATIVE.equals(actionName)) {
                try {
                    mList.clear();
                    specialListAdapter.notifyDataSetChanged();

                    for (int i = 0, j = rows.size(); i < j; i++){
                        mList.add(rows.getJSONObject(i));
                    }
                    if(total > (pageIndex * pageSize))
                        ptrClassicFrameLayout.setLoadMoreEnable(true);
                    else
                        ptrClassicFrameLayout.setLoadMoreEnable(false);
                    listView.setAdapter(specialListAdapter);
                } finally {
                    ptrClassicFrameLayout.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ptrClassicFrameLayout.refreshComplete();
                            specialListAdapter.notifyDataSetChanged();
                        }
                    }, 0);
                }
            } else if ((ConfigModel.SPECIAL_GET_NATIVE + "$more").equals(actionName)) {
                try {
                    for (int i = 0, j = rows.size(); i < j; i++){
                        mList.add(rows.getJSONObject(i));
                    }
                    if(total > (pageIndex * pageSize))
                        ptrClassicFrameLayout.setLoadMoreEnable(true);
                    else
                        ptrClassicFrameLayout.setLoadMoreEnable(false);
                } finally {
                    ptrClassicFrameLayout.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(total > (pageIndex * pageSize))
                                ptrClassicFrameLayout.loadMoreComplete(true);
                            else
                                ptrClassicFrameLayout.loadMoreComplete(false);
                            specialListAdapter.notifyDataSetChanged();
                        }
                    }, 0);
                }
            }
        }catch (Exception e){

        }
    }

    @Override
    public void onActionFailed(String errorVal, String actionName) {
        if ((ConfigModel.SPECIAL_GET_NATIVE + "$more").equals(actionName)){
            pageIndex--;
        }
        ptrClassicFrameLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrClassicFrameLayout.refreshComplete();
            }
        }, 0);
    }
}

